package com.ycsd.invest.order.business.apiplugin;

import com.drew.lang.annotations.NotNull;
import com.twelvemonkeys.lang.StringUtil;
import com.ycsd.invest.order.business.dto.ExampleModelDto;
import com.ycsd.invest.order.business.dto.StudyFormDto;
import com.ycsd.invest.order.common.utils.DynamicObjectUtil;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.openapi.common.constant.HttpStatus;
import kd.bos.openapi.common.custom.annotation.*;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.openapi.common.result.OpenApiFile;
import kd.bos.openapi.service.context.ServiceApiContext;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import org.springframework.validation.annotation.Validated;


import javax.validation.Valid;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Descrіption: 学习开发平台自定义API
 * @Author: yn
 * @Date: 2025/6/23 10:25
 */
@ApiController(value = "/dev", desc = "学习表单测试API")
@ApiMapping("/openapi/study")
public class TestStudyApi implements Serializable {

    @ApiPostMapping("query")
    public CustomApiResult<Map<String, Object>> query(@ApiParam("billno") String billno) {
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("ycsd_study_form",
                new QFilter[]{new QFilter("billno", QCP.equals, billno)});
        HashMap<String, Object> hashMap = DynamicObjectUtil.readPropValue(dynamicObject);
        HashMap<String, Object> rs = new HashMap<>();
        rs.put("id", hashMap.get("id"));
        rs.put("billno", hashMap.get("billno"));
        rs.put("color", hashMap.get("color"));
        return CustomApiResult.success(rs);
    }

    @ApiPostMapping("save")
    public CustomApiResult<Boolean> save(@Valid @ApiRequestBody("表单消息") StudyFormDto dto) {
        DynamicObject ycsdStudyForm = BusinessDataServiceHelper.newDynamicObject("ycsd_study_form");
        ycsdStudyForm.set("amount", dto.getAmount());
        ycsdStudyForm.set("multiplyval", dto.getMultiplyval());
        ycsdStudyForm.set("number", dto.getNumber());
        ycsdStudyForm.set("number_two", dto.getNumber_two());
        ycsdStudyForm.set("sum_val", dto.getSum_val());
        //设置自定义编码后 获取编码
        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(ycsdStudyForm.getDataEntityType().getName(),
                ycsdStudyForm, String.valueOf(RequestContext.get().getOrgId()));
        String number = CodeRuleServiceHelper.getNumber(codeRule, ycsdStudyForm);
        ycsdStudyForm.set("billno", number);
        //获取单据类型
        DynamicObject type = BusinessDataServiceHelper.loadSingle("bos_billtype",
                new QFilter[]{new QFilter("number", QCP.equals, "ycsd_study_form")});
        ycsdStudyForm.set("form_type",type);
        //单据状态
        ycsdStudyForm.set("billstatus","A");
        OperationResult result = OperationServiceHelper.executeOperate("save",
                "ycsd_study_form", new DynamicObject[]{ycsdStudyForm}, OperateOption.create());
        return CustomApiResult.success(result.isSuccess());
    }


    @ApiPostMapping(value = "/uploadFile", desc = "上传文件流")
    public CustomApiResult<String> uploadFile(@NotNull @ApiParam("订单号") String billno,
                                              @ApiParam("文件流") OpenApiFile file) {
        /*
            如何开发API支持文件流处理：
            ==============================
            1. 上传文件时请求消息格式应设置为：multipart/form-data。
            2. 定义一个OpenApiFile类型的入参（可以定义多个)，插件中可以获取到上传的文件名/类型/文件流(byte[])
            3. 其他参数（如业务单号、ID）按正常的参数定义即可。
            4. 如果要返回文件流或下载文件请设置http头的AcceptType为：application/octet-stream，
                   如果只返回文件处理结果信息可以设置http头ContentType为：application/json。
            注：由于性能考虑单次文件传输大小最多为30M。
         */

        if (StringUtil.isEmpty(billno) || file == null || file.getFileData() == null) {
            //手动设置http状态码406
            ServiceApiContext.getResponse().setHttpStatus(HttpStatus.NOT_ACCEPTABLE.getStatusCode());
            //返回失败错误码：errorCode：900101（业务自行约定）  & status=false
            return CustomApiResult.fail("900101", "订单号billNo及文件流file1不能为空。");
        }
        String msg = "您的订单号：" + billno + "，上传的文件名是：" + file.getFileName() + "，类型是：" + file.getContentType()
                + "，文件长度为（Bytes）：" + file.getFileData().length;
        return CustomApiResult.success(msg);
    }

    @Validated(ExampleModelDto.Save.class)
    @ApiPostMapping("/testValid")
    public CustomApiResult<Boolean> testValid(@Valid @ApiRequestBody(value = "参数信息") ExampleModelDto model) {
        String parameter1 = model.getParameter1();
        String parameter2 = model.getParameter2();
        String parameter3 = model.getParameter3();
        String parameter4 = model.getParameter4();
        CustomApiResult<Boolean> customApiResult = new CustomApiResult<>();
        customApiResult.setData(true);
        customApiResult.setErrorCode("");
        customApiResult.setMessage("");
        customApiResult.setStatus(true);
        return customApiResult;
    }



}
